package com.yuchengtech.simpleServer.core.handler;

import java.io.IOException;
import java.net.Socket;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ResourceNotFoundException;

import sun.net.www.protocol.http.HttpURLConnection;

import com.yuchengtech.simpleServer.core.HttpRequest;
import com.yuchengtech.simpleServer.core.HttpResponse;
import com.yuchengtech.simpleServer.core.SimpleHttpServer;


public class VelocityHandler implements Handler{

	private static final VelocityHandler HANDLER=new VelocityHandler();
	//初始化并取得Velocity引擎
	VelocityEngine ve = new VelocityEngine();
	
	public VelocityHandler() {
		ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,SimpleHttpServer.getBasePath());
		ve.setProperty(Velocity.INPUT_ENCODING,"utf-8");
		ve.setProperty(Velocity.OUTPUT_ENCODING,"utf-8");
		ve.init();
	}
	public void doHandle(Socket connection, HttpRequest request,
			HttpResponse response) {
		try {
			Map<String,Object> root=request.getAttributeMap();
			root.putAll(request.getParameterMap());
			
			VelocityContext context=new VelocityContext();
			context.put("request",request);
			context.put("reqScope",root);
			try
			{
			Template t= ve.getTemplate(request.getNowUrl());
			t.merge(context, response.getPrintWriter());
			}catch(ResourceNotFoundException ee)
			{
				response.setStatusCode(HttpURLConnection.HTTP_NOT_FOUND);
			}
			response.doResponse();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static VelocityHandler getSingleHandler()
	{
		return HANDLER;
	}

}
